import 'package:flutter/material.dart';
import '../model/order.dart';
import '../repository/order_repository.dart';

class OrderTab extends StatefulWidget {
  final OrderRepository repository;
  final String userId;

  const OrderTab({
    Key? key,
    required this.repository,
    required this.userId,
  }) : super(key: key);

  @override
  _OrdersTabState createState() => _OrdersTabState();
}

class _OrdersTabState extends State<OrderTab> {
  List<Order> _orders = [];
  bool _isLoading = false;
  String _error = '';

  @override
  void initState() {
    super.initState();
    _loadOrders();
  }

  Future<void> _loadOrders() async {
    setState(() {
      _isLoading = true;
      _error = '';
    });

    try {
      final response = await widget.repository.getUserOrders(widget.userId);

      if (response.data != null) {
        setState(() {
          _orders = response.data!;
          _isLoading = false;
        });
      } else {
        setState(() {
          _error = response.message ?? "Failed to load orders";
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _error = "Error: $e";
        _isLoading = false;
      });
    }
  }

  Future<void> _createSampleOrder() async {
    final newOrder = Order(
      id: "", // Will be generated by server
      userId: widget.userId,
      items: [
        OrderItem(
          id: "201",
          name: "Sample Product",
          price: 49.99,
          quantity: 1,
        ),
        OrderItem(
          id: "202",
          name: "Another Product",
          price: 19.99,
          quantity: 2,
        ),
      ],
      total: 89.97,
      status: "pending",
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
    );

    final response = await widget.repository.createOrder(newOrder);

    if (response.data != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Order created: ${response.data!.id}')),
      );
      _loadOrders();
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to create order: ${response.message}')),
      );
    }
  }

  Future<void> _updateOrderStatus(Order order, String newStatus) async {
    final response = await widget.repository.updateOrderStatus(
      order.id,
      newStatus,
    );

    if (response.data != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Order status updated to $newStatus')),
      );
      _loadOrders();
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to update order: ${response.message}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_error.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_error, style: const TextStyle(color: Colors.red)),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _loadOrders,
              child: const Text('Retry'),
            ),
          ],
        ),
      );
    }

    if (_orders.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('No orders found'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _createSampleOrder,
              child: const Text('Create Sample Order'),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            itemCount: _orders.length,
            itemBuilder: (context, index) {
              final order = _orders[index];
              return Card(
                margin: const EdgeInsets.all(8),
                child: ExpansionTile(
                  title: Text('Order #${order.id}'),
                  subtitle: Text(
                    '${order.status.toUpperCase()} - \$${order.total.toStringAsFixed(2)}',
                    style: TextStyle(
                      color: _getStatusColor(order.status),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text('Items:', style: TextStyle(fontWeight: FontWeight.bold)),
                          ...order.items.map((item) => ListTile(
                            title: Text(item.name),
                            subtitle: Text('Quantity: ${item.quantity}'),
                            trailing: Text('\$${(item.price * item.quantity).toStringAsFixed(2)}'),
                          )),
                          const SizedBox(height: 10),
                          Text('Created: ${_formatDate(order.createdAt)}'),
                          Text('Updated: ${_formatDate(order.updatedAt)}'),
                          const SizedBox(height: 10),
                          Wrap(
                            spacing: 8,
                            children: [
                              if (order.status != 'shipped')
                                ElevatedButton(
                                  onPressed: () => _updateOrderStatus(order, 'shipped'),
                                  child: const Text('Mark as Shipped'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.blue,
                                  ),
                                ),
                              if (order.status != 'delivered')
                                ElevatedButton(
                                  onPressed: () => _updateOrderStatus(order, 'delivered'),
                                  child: const Text('Mark as Delivered'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.green,
                                  ),
                                ),
                              if (order.status != 'cancelled')
                                ElevatedButton(
                                  onPressed: () => _updateOrderStatus(order, 'cancelled'),
                                  child: const Text('Cancel Order'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.red,
                                  ),
                                ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Create New Order'),
            onPressed: _createSampleOrder,
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(double.infinity, 50),
            ),
          ),
        ),
      ],
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'processing':
        return Colors.blue;
      case 'shipped':
        return Colors.purple;
      case 'delivered':
        return Colors.green;
      case 'cancelled':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _formatDate(DateTime date) {
    return '${date.day}/${date.month}/${date.year} ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
  }
}